package com.ziq.zcamp.view;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;

import androidx.annotation.Nullable;

import com.ziq.zcamp.manager.GlobalContextManager;

public class LoadingView extends androidx.appcompat.widget.AppCompatImageView {
    private AnimationDrawable frameAnim;

    int length = 24;

    public LoadingView(Context context) {
        this(context, null);
    }

    public LoadingView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        frameAnim = new AnimationDrawable();
        for(int i = 0; i < length; i++){
            int resId = getResByIndex(i);
            if(resId != 0){
                frameAnim.addFrame(GlobalContextManager.INSTANCE.getResources().getDrawable(resId), 1000/length);
            }
        }
        setImageDrawable(frameAnim);
    }

    public void startAnim(){
        frameAnim.start();
    }

    public void stopAnim(){
        frameAnim.stop();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        frameAnim.stop();
    }

    public boolean selectDrawableProgress(int progress){
        int level = (int) (progress / 100.0 * 24);
        return frameAnim.selectDrawable(level);
    }

    public int getResByIndex(int index){
        ApplicationInfo appInfo = GlobalContextManager.INSTANCE.getAppContext().getApplicationInfo();

        int resID = GlobalContextManager.INSTANCE.getResources().getIdentifier("loading_"+index, "drawable", appInfo.packageName);
        if(resID == index){
            return 0;
        }
        return resID;
    }
}